package itsm.isperp.module.controller.customer.request;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.VUserAccount;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.entity.customer.CusCustomerComment;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.service.announcement.AnnouncementService;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.app.UserAccountService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.customer.CusCustomerCommentService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.individuation.IddIndividuationFormService;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jdbc.support.DatabaseType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2016-4-27
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("customer/help/request/api")
public class CusHelpRequestApiController {

  @Autowired
  IcdIncidentService icdIncidentService;

  @Autowired
  JdbcTemplate jdbcTemplate;

  @Autowired
  AppUserService appUserService;

  // 公告列表

  @RequestMapping("getAnnotation")
  @ResponseBody
  public Object getAnnotation(HttpServletRequest req, String callback) {
    try {
      String rownum = req.getParameter("row");
      if (StringUtils.isEmpty(rownum)) {
        rownum = "5";
      }
      AnnouncementService announcementService = ContextHolder
          .getSpringBean("announcementService");

      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(null);
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;

    }
  }

  // 公告详情
  @RequestMapping("getAnnotationDetail")
  @ResponseBody
  public Object getAnnotationDetail(HttpServletRequest req, String callback) {
    try {
      String id = req.getParameter("id");
      AnnouncementService announcementService = ContextHolder
          .getSpringBean("announcementService");
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          announcementService.findOne(id));
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }

  }

  /*
   * 个人信息
   */
  @RequestMapping("getUserInfoById")
  @ResponseBody
  public Object getUserInfoById(HttpServletRequest req, JqGridRequest request,
      String callback) {
    try {

      AppUserService appUserService = ContextHolder
          .getSpringBean("appUserService");
      String userId = ContextHolder.getLoginUser().getId();

      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          appUserService.findOneToMap(userId));
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

  /*
   * 个人基本信息提交
   */
  @RequestMapping("userInfoSaveOrUpdate")
  @ResponseBody
  public Object userInfoSaveOrUpdate(HttpServletRequest req, String callback,
      JqGridRequest request, String fullname, String appDepartmentId,
      String gender) {
    try {

      ResultMessage result = new ResultMessage();
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
      mappingJacksonValue.setJsonpFunction(callback);
      AppUserService appUserService = ContextHolder
          .getSpringBean("appUserService");
      String userId = ContextHolder.getLoginUser().getId();
      AppUser appuser = appUserService.findOne(userId);
      appuser.setFullname(fullname);
      AppDepartmentService appDepartmentService = ContextHolder
          .getSpringBean("appDepartmentService");
      AppDepartment appDepartment = appDepartmentService
          .findOne(appDepartmentId);
      if (appDepartment == null) {
        result = ResultMessage.failure("您提交的公司信息有误，修改失败！");
        return mappingJacksonValue;
      }
      appuser.setAppDepartmentId(appDepartmentId);
      appuser.setGender(gender);
      appUserService.saveOrUpdate(appuser);
      result = ResultMessage.success("修改成功！");

      return mappingJacksonValue;
    } catch (Exception e) {

      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure("修改失败！"));

      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }

  }

  /*
   * 部门信息获取
   */
  @RequestMapping("listDepartmentByName")
  @ResponseBody
  public Object listDepartmentByName(String callback, HttpServletRequest req,
      JqGridRequest request) {
    try {
      String name = req.getParameter("name");
      String userType = req.getParameter("userType");

      AppUserService appUserService = ContextHolder
          .getSpringBean("appUserService");

      List<Map<String, Object>> appDepartments = null;
      /*
       * for (Map<String, Object> appDepartment : appDepartments) { String
       * department = (String) appDepartment.get("treenode_name_path");
       * appDepartment.put("name", itsm.isperp.framework.utils.StringUtils
       * .subStrDepartment(department)); }
       */

      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          appDepartments);

      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }

  }

  /*
   * //事件申报
   */
  @RequestMapping("incidentSubmit")
  @ResponseBody
  public Object incidentSubmit(HttpServletRequest req, String callback) {
    try {
      AppUser user = (AppUser) ContextHolder.getLoginUser();
      BpmProcessRunService bpmProcessRunService = ContextHolder
          .getSpringBean("bpmProcessRunService");
      IcdIncidentService icdIncidentService = ContextHolder
          .getSpringBean("icdIncidentService");
      String userMobile = req.getParameter("userMobile");
      String id = req.getParameter("id");
      IcdIncident model = null;
      if (StringUtils.isNotBlank(id))
        model = icdIncidentService.findOne(id);
      else
        model = new IcdIncident();
      model.setDescription(req.getParameter("description"));
      model.setCusUserId(user.getId());
      if (this.icdIncidentService.exists(model.getId())) {
        icdIncidentService.saveOrUpdate(model, req);
        IcdIncident icd = icdIncidentService.findOne(model.getId());
        String nextTaskId = req.getParameter("nextTaskId");
        String nextTransitionId = req.getParameter("nextTransitionId");
        String processId = icd.getProcessId();

        bpmProcessRunService.gotoNextSetp(user.getUsername(),
            "incidentProcess", nextTaskId, nextTransitionId, processId, id,
            null, "", 0);
      } else {
        // 启动新流程
        String linkmanName = user.getFullname();
        String userTel = user.getTel();
        model.setLinkmanName(linkmanName);
        String userTel_ = StringUtils.isEmpty(userTel) ? "" : userTel + "/";
        model.setLinkmanPhone(userTel_ + userMobile);
      }
      model.setSource("Web");
      icdIncidentService.saveOrUpdate(model);
      bpmProcessRunService.startProcess(user.getUsername(), "incidentProcess",
          model.getId(), "");
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.newInstance(true));
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }
  
  
  @RequestMapping("listTodoIncidentByUserId")
  @ResponseBody
  public Object listTodoIncidentByUserId(String callback,
      HttpServletRequest req, JqGridRequest request) {
    try {

      AppUser user = (AppUser) ContextHolder.getLoginUser();
      String pageIndex = req.getParameter("page");
      String rowIndex = req.getParameter("row");
      String userName=user.getUsername();

      int currentPage = 1;
      int row = 600000000;
      if (StringUtils.isNotEmpty(pageIndex)) {
        currentPage = Integer.parseInt(pageIndex);
      }
      if (StringUtils.isNotEmpty(rowIndex)) {
        row = Integer.parseInt(rowIndex);
      }

      String msgSql = "SELECT are_from_customer  FROM (SELECT are_from_customer,source_id  FROM app_message_success WHERE message_type='LEAVEMSG' ";

      if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
        msgSql += " AND ROWNUM <= 1  ORDER BY create_date DESC";
      } else {
        msgSql += "  ORDER BY create_date DESC LIMIT 1 ";

      }
      msgSql += ")t WHERE  source_id=icd_incident.id";
      String[] columns = { "id", "code", "priority_name", "icd_category_name",
          "title", "create_date", "expect_time", "status",
          " (" + msgSql + ") AS sla_status" };
      request.setSelectColumns(columns);
      request
      .setSearchString(" process_id IN (SELECT DISTINCT  PROC_INST_ID_ FROM (SELECT  task.PROC_INST_ID_ FROM ACT_RU_TASK task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' AND task.ASSIGNEE_ = '"+userName+"'  UNION ALL "
          + " SELECT  task.PROC_INST_ID_  FROM act_ru_identitylink task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' "
          + "     AND task.USER_ID_ = '"+userName+"' AND task.type_ = 'candidate') task) and (status in('重新提交','退回'))");
      request.addFilterRule("status", JqGridFilterRuleOp.ne, "已关闭");

      request.setPageable(true);
      request.setRows(15);

      if (StringUtils.isNotEmpty(pageIndex)) {
        currentPage = Integer.parseInt(pageIndex);
      }
      request.setPage(currentPage);

      DataResponse<IcdIncident> response = this.getIncidentList(user, request);
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          response.toPage());

      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }


  @RequestMapping("listDoingIncidentByUserId")
  @ResponseBody
  public Object listDoingIncidentByUserId(String callback,
      HttpServletRequest req, JqGridRequest request) {
    try {

      AppUser user = (AppUser) ContextHolder.getLoginUser();
      String pageIndex = req.getParameter("page");
      String rowIndex = req.getParameter("row");

      int currentPage = 1;
      int row = 600000000;
      if (StringUtils.isNotEmpty(pageIndex)) {
        currentPage = Integer.parseInt(pageIndex);
      }
      if (StringUtils.isNotEmpty(rowIndex)) {
        row = Integer.parseInt(rowIndex);
      }

      String msgSql = "SELECT are_from_customer  FROM (SELECT are_from_customer,source_id  FROM app_message_success WHERE message_type='LEAVEMSG' ";

      if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
        msgSql += " AND ROWNUM <= 1  ORDER BY create_date DESC";
      } else {
        msgSql += "  ORDER BY create_date DESC LIMIT 1 ";

      }
      msgSql += ")t WHERE  source_id=icd_incident.id";
      String[] columns = { "id", "code", "priority_name", "icd_category_name",
          "title", "create_date", "expect_time", "status",
          " (" + msgSql + ") AS sla_status" };
      request.setSelectColumns(columns);
      request.setSearchString(" cus_user_id='" + user.getId() + "'");
      request.addFilterRule("status", JqGridFilterRuleOp.ne, "已关闭");

      request.setPageable(true);
      request.setRows(15);

      if (StringUtils.isNotEmpty(pageIndex)) {
        currentPage = Integer.parseInt(pageIndex);
      }
      request.setPage(currentPage);

      DataResponse<IcdIncident> response = this.getIncidentList(user, request);
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          response.toPage());

      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

  // 取得
  private DataResponse<IcdIncident> getIncidentList(AppUser user,
      JqGridRequest request) {

    request.addFilterRule("title", JqGridFilterRuleOp.ne, "");
    request.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, user.getId());
    request.setSort("create_date", Direction.DESC);

    return icdIncidentService.findAll(request);

  }

  @RequestMapping("listCustomerComment")
  @ResponseBody
  public Object listCustomerComment(HttpServletRequest req, String callback) {
    try {
      String reqType = req.getParameter("reqType");
      String state = req.getParameter("state");
      String pageStr = req.getParameter("page");
      String rowsStr = req.getParameter("row");
      int row = 1000000000;
      int page = 1;
      if (StringUtils.isNotBlank(pageStr)) {
        page = Integer.parseInt(pageStr);
      }
      if (StringUtils.isNotBlank(pageStr)) {
        row = Integer.parseInt(rowsStr);
      }
      CusCustomerCommentService cusCustomerCommentService = ContextHolder
          .getSpringBean("cusCustomerCommentService");
      PageResponse<CusCustomerComment> pageResponse = cusCustomerCommentService
          .findAll().toPage();

      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          pageResponse);
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

  @RequestMapping("listRequestByReqType")
  @ResponseBody
  public Object listRequestByReqType(HttpServletRequest req, String callback) {
    try {
      ResultMessage resultMessage = ResultMessage.newInstance(true);
      String reqType = req.getParameter("reqType");
      if (StringUtils.isNotEmpty(reqType)) {
        IddIndividuationFormService iddIndividuationFormService = ContextHolder
            .getSpringBean("iddIndividuationFormService");
        resultMessage.setData(iddIndividuationFormService
            .findOne("27557365312900027"));
      }
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          resultMessage);
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

  /**
   * 获取相关服务
   * 
   * @param req
   * @param callback
   * @return
   */
  @RequestMapping("listRelateRequestByReqType")
  @ResponseBody
  public Object listRelateRequestByReqType(HttpServletRequest req,
      String callback) {
    try {
      ResultMessage resultMessage = new ResultMessage();
      String reqType = req.getParameter("reqType");
      if (StringUtils.isNotEmpty(reqType)) {

      }
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          resultMessage);
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

  /**
   * 获取整体评论
   * 
   * @param req
   * @param callback
   * @return
   */
  @RequestMapping("listOverallComment")
  @ResponseBody
  public Object listOverallComment(HttpServletRequest req, String callback) {
    try {
      String reqType = req.getParameter("reqType");
      Map<String, Object> overallComment = new HashMap<String, Object>();
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          overallComment);
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

  /**
   * 获取服务地址列表
   * 
   * @param req
   * @param callback
   * @return
   */
  @RequestMapping("listReqAddress")
  @ResponseBody
  public Object listReqAddress(HttpServletRequest req, String callback) {
    try {

      ResultMessage result = ResultMessage.newInstance(true);
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    } catch (Exception e) {
      MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
          ResultMessage.failure());
      mappingJacksonValue.setJsonpFunction(callback);
      return mappingJacksonValue;
    }
  }

}
